#include "socket_gather_read.h"

#include "Socket_Private_acl.h"
#include "Log.h"
#ifdef WIN32
#define usleep(x) Sleep(x)
#endif

namespace G_VALUE {
	unsigned int gatherReadUpT=0;
};

SocketGatherRead::SocketGatherRead(void)
	: running(true) 
	, socket_acl(NULL)
	, socket_cache_queue(QueueDataSingle<DataFromChannel>::getInstance())
{
}

SocketGatherRead::~SocketGatherRead(void)
{
	running = false;
}

void SocketGatherRead::setPrivateDataPtr(SocketPrivate_ACL *socket_acl_)
{
	if (NULL != socket_acl_)
	{
		socket_acl = socket_acl_;
	}
}

void* SocketGatherRead::run()
{
	if (NULL == socket_acl) 
	{
		CLogger::createInstance()->Log(MsgError,
			"MySocketExxRD start fail for socket_acl is NULL"
			",[%s %s %d]!"
			, __FILE__, __FUNCTION__, __LINE__);
		return 0;
	}
	std::map<KeyObj_Client, RDClient> bufs;
	while (running)
	{
		G_VALUE::gatherReadUpT = static_cast<unsigned int>(time(NULL));
		int re = socket_acl->Read(bufs);
		if (re < 0) 
		{
#ifdef _DEBUG
			Print_WARN("Read Data Failed \n!");
#else
			;
#endif
		}
		else 
		{
			try {
				std::map<KeyObj_Client, RDClient>::iterator it = bufs.begin();
				while (it != bufs.end())
				{
					unsigned char * buff = it->second.Buf;
					int start_pos = 0;
					unsigned char ctype = 0;
					// printf("read:");
					for (int i = 0; i < it->second.len; ++i)
					{
						// printf("%02X ",buff[i]);
						if (buff[i] > 0xf0) 
						{
							if (buff[i] == 0xff) 
							{
								if (ctype) 
								{
									ctype = 0;
									DataFromChannel rdata(buff + start_pos, i - start_pos + 1, it->first.m_ipStr);
									socket_cache_queue->add(rdata);
									start_pos = i + 1;
								}
							}
							else 
							{
								ctype = buff[i];
								start_pos = i;
							}
						}
					}
					// printf("\n");
					buff = NULL;
					if (start_pos < it->second.len)
					{
						RDClient _newrd(it->second.Buf + start_pos, it->second.len - start_pos);
						it->second = _newrd;
						it++;
					}
					else 
					{
#ifdef WIN32
						it = bufs.erase(it);
#else
						std::map<KeyObj_Client, RDClient>::iterator ittemp = it++;
						bufs.erase(ittemp);
#endif
					}
				}
			}
			catch (const std::exception& e)
			{
				CLogger::createInstance()->Log(MsgError,
					"Data Deserialize false[%s],[%s %s %d]!"
					, e.what()
					, __FILE__, __FUNCTION__, __LINE__);
			}
			catch (...) 
			{
				CLogger::createInstance()->Log(MsgError,
					"Data Deserialize false,[%s %s %d]!"
					, __FILE__, __FUNCTION__, __LINE__);
			}
		}
		usleep(1);
		}
	return 0;
};
